<?php
/**
 * 数据库操作类
 * @author "dengqihua"
 *
 */
class DB{
	private $db;
	private $host = 'hdm-063.hichina.com';
	private $dbname = 'hdm0630476_db';
	private $username = 'hdm0630476';
	private $passwd = 'JUSMOR2014';
	private $table;
	
	public function __construct($table = null) {
		if(! empty($table)) {
			$this->table = $table;
		}
		$dsn = 'mysql:dbname='.$this->dbname.'; host='.$this->host;
		try {
			$this->db = new PDO($dsn, $this->username, $this->passwd);
			$this->db->query('set names utf8');
		} catch (PDOException $e) {
			echo '数据库连接失败：'.$e->getMessage();
		}
	}
	
	/**
	 * 查询单条记录
	 * @param unknown $table
	 * @param string $fields
	 * @param unknown $condition
	 * @return boolean|mixed
	 */
	public function fetch($condition = '', $fields = '*', $table='') {
		if(! empty($fields) && $fields != '*') {
			$fields = $this->setFields($fields);
		}
		if(! empty($condition)) {
			$condition = $this->setCondition($condition);
		}
		if(! empty($table)) {
			$this->table = $table;
		}
		
		$query = 'select '.$fields.' from `'.$this->table.'` where 1 '.$condition.' limit 1';
		$stmt = $this->db->prepare($query);
		$stmt->execute();
		$retult = $stmt->fetch(PDO::FETCH_ASSOC);
		if($retult) {
			return $retult;
		} else {
			return false;
		}
	}
	
	/**
	 * 查询多条记录
	 * @param unknown $table
	 * @param string $fields
	 * @param string $condition
	 * @param string $limit
	 * @param number $offset
	 * @param string $order
	 * @return boolean|multitype:
	 */
	public function fetchAll($condition = '', $fields = '*', $table = '', $limit = '', $offset = 0, $order = '') {
		if(! empty($fields) && $fields != '*') {
			$fields = $this->setFields($fields);
		}
		if(! empty($condition)) {
			$condition = $this->setCondition($condition);
		}
		if(! empty($order)) {
			$order = $this->setOrder($order);
		}
		if(! empty($table)) {
			$this->table = $table;
		}
		
		$limits = $this->setLimit($limit, $offset);
		
		$query = 'select '.$fields.' from `'.$this->table.'` where 1 '.$condition.' '.$order.' '.$limits;
	
		$stmt = $this->db->prepare($query);
		$stmt->execute();
		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
		if($result) {
			return $result;
		} else {
			return false;
		}
	}
	
	/**
	 * 插入数据
	 * @param array $data	必须是数组类型
	 * @param string $table	字符串类型
	 * @return boolean  插入成功后，返回最后一次插入数据的主键id；插入失败返回false
	 */
	public function insert($data, $table = '') {
		if(empty($data) || ! is_array($data)) {
			return false;
		}
		if(! empty($table)) {
			$this->table = $table;
		}
	
		//处理数据
		$data_keys = array_keys($data);
		$data_values = array_values($data);
	
		$fields = '`'.implode('`,`', $data_keys).'`';
		$values = '';
		for ($i=0; $i < count($data_values); $i++) {
			$values .= '?,';
		}
		$values = trim($values, ',');
		$query = 'insert into `'.$this->table.'`('.$fields.') values('.$values.')';
		$stmt = $this->db->prepare($query);
		$result = $stmt->execute($data_values);
		if($result) {
			return $this->db->lastInsertId();
		} else  {
			return false;
		}
	}
	
	/**
	 * 更新数据
	 * @param unknown $table
	 * @param unknown $data	必须是数组形式
	 * @param unknown $condition	
	 * @return boolean|string
	 */
	public function update($data, $condition, $table = '' ) {
		if( empty($condition)) {
			return false;
		}
		if(! empty($table)) {
			$this->table = $table;
		}
		$query = 'update `'.$this->table.'` set '.$this->setData($data).' where 1 '.$this->setCondition($condition);
		$stmt = $this->db->prepare($query);
		$result = $stmt->execute();
		if($result) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 删除数据
	 * @param unknown $table
	 * @param unknown $condition
	 * @return boolean
	 */
	public function delete($condition, $table = '') {
		if(empty($condition)) {
			return false;
		}
		if(! empty($table)) {
			$this->table = $table;
		}
		$query = 'delete from `'.$this->table.'` where 1'.$this->setCondition($condition);
		$stmt = $this->db->prepare($query);
		$result = $stmt->execute();
		if($result) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 查询符合条件的数据数量
	 * @param unknown $condition
	 * @param string $table
	 * @return boolean|mixed
	 */
	public function fetchCount($condition, $table = '') {
		if(empty($condition)) {
			return false;
		}
		if(!empty($table)) {
			$this->table = $table;
		}
		
		$query = 'select count(*) as total from `'.$this->table.'` where 1 '.$this->setCondition($condition);
		$stmt = $this->db->prepare($query);
		$stmt->execute();
		$result = $stmt->fetch();
		if($result) {
			return $result['total'];
		} else {
			return false;
		}
	}
	
	/**
	 * 设置条件，拼接成sql形式的语句
	 * @param unknown $condition
	 * @return boolean|string
	 */
	private function setCondition($condition) {
		if(empty($condition)) {
			return false;
		}
		$conditions = '';
		if(is_array($condition)) {
			$condition_key = array_keys($condition);
			$condition_values = array_values($condition);
		
			foreach ($condition_key as $key=>$val) {
				$conditions .= "`".$val."` = '".$condition_values[$key]."'";
				if($val != end($condition_key)) {
					$conditions .= ' and ';
				}
			}
			$conditions = ' and '.$conditions;
		} else {
			$conditions = ' and '.$condition;
		}
		return $conditions;
	}
	
	/**
	 * 设置字段，拼接成符合sql格式的字段
	 * @param unknown $fields
	 * @return boolean|string
	 */
	private function setFields($fields) {
		if(empty($fields)) {
			return false;
		}
		$fields = '`'.str_replace(', ', '`,`', $fields).'`';
		return $fields;
	}
	
	/**
	 *设置排序
	 */
	private function setOrder($order) {
		if(empty($order)) {
			return false;
		}
		$orders = '';
		if(is_array($order)) {
			$order_key = array_keys($order);
			$order_values = array_values($order);
			
			foreach ($order_key as $key=>$val) {
				$orders .= "`".$val."` ".$order_values[$key]." , ";
			}
			$orders = ' order by '.trim($orders, ' ,');
			
		} else {
			$orders = ' order by '.$order;
		}

		return $orders;
	}
	
	/**
	 * 设置查询条数
	 * @param unknown $limit
	 * @param unknown $offset
	 * @return string
	 */
	private function setLimit($limit, $offset) {
		$limits = '';
		if(empty($limit)) {
			return $limits;
		}
		$limits = ' limit '.$offset.','.$limit;
		return $limits;
	}
	
	/**
	 * 设置更新的数据
	 * @param unknown $data
	 * @return boolean|string
	 */
	private function setData($data) {
		if(empty($data)) {
			return false;
		}
		$datas = '';
		$data_key = array_keys($data);
		$data_values = array_values($data);
		foreach ($data_key as $key=>$val) {
			$datas .= "`".$val."` = '".$data_values[$key]."',";
		}
		$datas = trim($datas, ',');
		return $datas;
	}
	
	/**
	 * 原型打印数组
	 * @param unknown $result
	 */
	public function __print_r($result, $flag = false) {
		echo '<pre>';
		print_r($result);
		echo '</pre>';
		if($flag) {
			exit();
		}
	}
	
}